package com.rhett.autoMyBatis.utils;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


public class DBUtils {

    public static <T> List<T> query(DBConnection dbConnection, String sql, Class<T> tClass) throws Exception{
        Class.forName(dbConnection.getDriver());
        String url = dbConnection.getUrl() + dbConnection.getDb();
        Connection conn = null;
        conn = DriverManager.getConnection(url, dbConnection.getUsername(), dbConnection.getPassword());

        // 3. 获得语句执行平台,通过数据库连接对象,获取到SQL语句的执行者对象
        //conn对象,调用方法 Statement createStatement() 获取Statement对象,将SQL语句发送到数据库
        //返回的是Statement接口的实现类对象,在MySQL驱动程序中
        Statement stat = null;
        stat = conn.createStatement();

        // 4. 执行sql语句
        //通过执行者对象调用方法执行SQL语句,获取结果
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<T> list = new ArrayList<>();
        // 5. 释放资源
        pstmt = conn.prepareStatement(sql);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            T t = tClass.newInstance();
            Field[] declaredFields = tClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                String name = declaredField.getName();
                declaredField.setAccessible(true);
                declaredField.set(t, rs.getString(name));
            }
            list.add(t);
        }
        stat.close();
        conn.close();
        return list;
    }

}
